// socket已经连接成功
var isConnectSocket = false;
// 判断心跳变量
var isHeart = false;
// 心跳失败次数
var heartBeatFailCount = 0;
// 心跳对象
var heartBeatTimeOut = null;
// 自动连接对象
var connectSocketTimeOut = null;
// 保存回调
var connectOptions = null;

var webSocket = {
    // socketUrl: 'ws://192.168.0.101:8088/yuhui/ws',
    // socketUrl: 'ws://120.78.60.115:8088/yuhui/ws',
    socketUrl: 'wss://www.xuegean.com/yuhui/ws',
    connectSocket: function (options) {
        if (options) {
          connectOptions=options;
        }
        var that = this
        wx.connectSocket({
            url: that.socketUrl,
            success: function (res) {
              if (connectOptions) {
                  // console.log(options)
                  // 成功回调
                  isConnectSocket = true;
                  that.timingConectSocket();
                  connectOptions.success && connectOptions.success(res);
                }
            },
            fail: function (res) {
                if (connectOptions) {
                  // 失败回调
                  connectOptions.fail && connectOptions.fail(res);
                }
                isConnectSocket = false
                that.timingConectSocket();
            }
        })
    },

    closeSocket: function (options) {
        var self = this;
        self.stopHeartBeat();   // 终止心跳
        isConnectSocket = false;// 标记关闭
        wx.closeSocket({
            success: function (res) {
                console.log('WebSocket 已关闭！');
                if (options) {
                    options.success && options.success(res);
                }
            },
            fail: function (res) {
                if (options) {
                    options.fail && options.fail(res);
                }
            }
        })
    },

    sendSocketMessage: function (options) {
        if (isConnectSocket) {
            wx.sendSocketMessage({
                data: options.data,
                success: function (res) {
                    if (options) {
                        options.success && options.success(res);
                    }
                },
                fail: function (res) {
                    if (options) {
                        options.fail && options.fail(res);
                    }
                }
            })
        } else {
            if (options) {
                options.fail && options.fail("web socket break link");
            }
        }
    },

    // 收到消息回调
    onSocketMessageCallback: function (message) {
      console.log(message)
    },

    // 开始心跳
    startHeartBeat: function () {
        // console.log('socket开始心跳')
        isHeart = true;
        this.heartBeat();
    },

    // 结束心跳
    stopHeartBeat: function () {
        console.log('socket结束心跳')
        var self = this;
        if (heartBeatTimeOut) {
            clearTimeout(heartBeatTimeOut);
            heartBeatTimeOut = null;
        }
        if (connectSocketTimeOut) {
            clearTimeout(connectSocketTimeOut);
            connectSocketTimeOut = null;
        }
    },

    // 心跳
    heartBeat: function () {
        var self = this;
        if (!isHeart) {
          return;
        }
        const param = {
          objectName: '100',
          message: '心跳发送成功'
        }
        self.sendSocketMessage({
            data: JSON.stringify(param),
            success: function (res) {
                console.log('socket心跳成功');
                if (isHeart) {
                    heartBeatTimeOut = setTimeout(() => {
                        self.heartBeat();
                    }, 1000 * 30);
                }
            },
            fail: function (res) {
                if (heartBeatFailCount > 2) {
                    // 重连
                    isHeart = false;
                    self.connectSocket();
                }
                if (isHeart) {
                    heartBeatTimeOut = setTimeout(() => {
                        self.heartBeat();
                    }, 1000 * 30);
                }
                heartBeatFailCount++;
            },
        });
    },

    // 重连
    timingConectSocket: function () {
      if (!isConnectSocket) {
        // 定时重连
        connectSocketTimeOut = setTimeout(() => {
          webSocket.connectSocket();
        }, 3000);
      } else {
        // 清除定时器
        clearTimeout(connectSocketTimeOut);
      }
    }
}

// 监听WebSocket连接打开事件。callback 回调函数
// wx.onSocketOpen(function (res) {
//     console.log('WebSocket连接已打开！')
//     // 如果已经调用过关闭function
//     if (isConnectSocket) {
//         webSocket.startHeartBeat();
//     }
// })


/**
 * 监听下websocket出现错误
 */
wx.onSocketError(function (res) {
    console.log('WebSocket连接打开失败，请检查！', res)
    isConnectSocket = false
    webSocket.timingConectSocket();
})

// /**
//  * 接收websocket返回消息
//  */
// wx.onSocketMessage(function (res) {
//     console.log('收到服务器内容：' + res.data)
//     webSocket.onSocketMessageCallback(res.data)
// })


/**
 * 监听关闭websocket
 */
wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！')
    isConnectSocket=false
    webSocket.timingConectSocket();
})

module.exports = webSocket;